package ar.com.osdepym.agregacionafip.adapters;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import ar.com.osdepym.agregacionafip.activities.DetalleActivity;
import ar.com.osdepym.agregacionafip.activities.R;
import ar.com.osdepym.agregacionafip.activities.context.AppContext;

public class CheckBoxDetailListAdapter extends ArrayAdapter<ContenedorCheckbox> {

	Context context;
	int layoutResourceId;
	List<ContenedorCheckbox> data = null;

	public CheckBoxDetailListAdapter(Context context, int layoutResourceId,
			List<ContenedorCheckbox> data) {
		super(context, layoutResourceId, data);
		this.layoutResourceId = layoutResourceId;
		this.context = context;
		this.data = data;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ContenedorCheckboxHolder holder = null;

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);

			holder = new ContenedorCheckboxHolder();
			holder.chkBox = (CheckBox) row.findViewById(R.id.checkBox1);
			holder.goDetail = (Button) row.findViewById(R.id.detail);

			row.setTag(holder);
		} else {
			holder = (ContenedorCheckboxHolder) row.getTag();
		}

		ContenedorCheckbox contenedorCheckbox = data.get(position);

		holder.chkBox.setText(contenedorCheckbox.getNombre());
		holder.chkBox.setChecked(contenedorCheckbox.getChecked());
		holder.chkBox.setTag(contenedorCheckbox);
		row.setBackgroundResource(contenedorCheckbox.getStateColor());

		if (contenedorCheckbox.getStateColor()
				.equals(R.drawable.background_red)) {
			holder.chkBox.setClickable(false);
		} else {
			holder.chkBox.setClickable(true);
			holder.chkBox.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					CheckBox c = (CheckBox) v;
					ContenedorCheckbox container = (ContenedorCheckbox) c
							.getTag();
					container.setChecked(c.isChecked());
				}
			});

		}
		holder.goDetail.setTag(contenedorCheckbox);
		holder.goDetail.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				((AppContext) context.getApplicationContext())
						.setContenedorDetalle((Contenedor) v.getTag());
				Intent i = new Intent(context, DetalleActivity.class);
				context.startActivity(i);
			}
		});

		return row;
	}

	static class ContenedorCheckboxHolder {
		CheckBox chkBox;
		Button goDetail;
	}

}
